package com.easy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.exception.BaseException;
import com.easy.common.exception.CustomException;
import com.easy.common.utils.ip.AddressUtils;
import com.easy.user.mapper.MembershipMapper;
import com.easy.user.pojo.Membership;
import com.easy.user.service.IMembershipService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MembershipServiceImpl extends ServiceImpl<MembershipMapper, Membership> implements IMembershipService {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    @Autowired
    private MembershipMapper membershipMapper;

    @Override
    public boolean addMembership(Membership membership) {
        int insert = 0;
        try {
            insert = membershipMapper.insert(membership);
        } catch (Exception e) {
            log.error("BC010:会员信息插入失败");
            throw new CustomException("BC010");
        }
        return insert > 0;
    }

    @Override
    public boolean deleteMembership(Membership membership) {
        int insert = 0;
        try {
            insert = membershipMapper.deleteById(membership.getId());
        } catch (Exception e) {
            log.error("BC011:会员信息删除失败");
            throw new CustomException("BC011");
        }
        return insert > 0;
    }

    @Override
    public boolean updateMembership(Membership membership) {
        int update = 0;
        try {
            LambdaUpdateWrapper<Membership> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Membership::getId, membership.getId());
            wrapper.set(Membership::getUserName, membership.getUserName());
            wrapper.set(Membership::getMembershipLevel, membership.getMembershipLevel());
            update = membershipMapper.update(null,wrapper);
        } catch (Exception e) {
            log.error("BC012:会员信息更新失败");
            throw new CustomException("BC012");
        }
        return update > 0;
    }

    @Override
    public Membership queryMembership(Membership membership) {
        LambdaQueryWrapper<Membership> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Membership::getId, membership.getId());
        try {
            membership = membershipMapper.selectOne(wrapper);
        } catch (Exception e) {
            log.error("BC013:查询会员信息失败");
            throw new CustomException("BC013");
        }
        return membership;
    }
}
